/**
 *
 * 简单的缓存模块, 会添加前缀，与 本地储存隔离
 * 除了get，ttl， 其他都是异步操作
 * 默认超时为 6000秒
 *
 */
let PREFIX = "_CACHE_1_1_"; // 前缀
function isInteger(obj) {
  return typeof obj === 'number' && obj % 1 === 0
}

function setSync(key, data, timeout) {
  let now = Math.round(new Date().getTime() / 1000);
  if (!timeout) {
    timeout = 6000;
  } else if (!isInteger(timeout)) {
    wx.showToast({
      title: "timeout必须为整数",
      icon: 'none',
      duration: 5000
    });
  }
  wx.setStorageSync(PREFIX + key, {"data": data, "timeout": now + timeout});
}

function set(key, data, timeout) {
  return new Promise((resolve, reject) => {
    let now = Math.round(new Date().getTime() / 1000);
    if (!timeout) {
      timeout = 6000;
    } else if (!isInteger(timeout)) {
      wx.showToast({
        title: "timeout必须为整数",
        icon: 'none',
        duration: 5000
      });
    }
    wx.setStorage({
      key: PREFIX + key,
      data: {"data": data, "timeout": now + timeout},
      success: ()=> {
        resolve()
      },
      fail: ()=> {
        reject()
      },
    });
  })
}


function del(key, success) {
  wx.removeStorage({key: PREFIX + key, success: success})
}


// 同步获取(超时或没有返回空)
function get(key) {
  let value = wx.getStorageSync(PREFIX + key);
  if (!value) return '';
  if (!value.timeout || !value.data) return '';
  let now = Math.round(new Date().getTime() / 1000);
  if (value.timeout < now) {//超时清除token
    if (key === "token") {  //重新获取token
      //返回之前的token
      return "";
    } else {
      console.log("删除" + key);
      del(key);
      //超时返回空
      return "";
    }
  }
  return value.data
}


function ttl(key) {
  let value = wx.getStorageSync(PREFIX + key);
  if (!value) return 0;
  if (!value.timeout || !value.data) return 0;
  let now = Math.round(new Date().getTime() / 1000);
  if (value.timeout < now) return 0;
  return value.timeout - now;
}

module.exports = {
  get: get,
  del: del,
  set: set,
  setSync: setSync,
  ttl: ttl
};
